package org.jash.mvp2206.user;

import android.content.Intent;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;

import org.jash.mvp2206.MainActivity2;
import org.jash.mvp2206.R;
import org.jash.mvp2206.mvp.BaseActivity;
import org.jash.mvp2206.utils.SPUtils;
import org.jash.mvp2206.video.VideoFragment;

public class LoginActivity extends BaseActivity<Construct.ILoginView, LoginPresenter> implements Construct.ILoginView {
    private EditText username;
    private EditText password;
    private ActivityResultLauncher<Intent> launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), i -> {
        Intent data = i.getData();
        if (data != null) {
            username.setText(data.getStringExtra("username"));
            password.setText(data.getStringExtra("password"));
        }
    });

    @Override
    protected int layoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initData() {
        presenter = new LoginPresenter();
    }

    @Override
    protected void initView() {
        username = findViewById(R.id.username);
        password = findViewById(R.id.password);
        findViewById(R.id.login).setOnClickListener(v -> presenter.login(username.getText().toString(), password.getText().toString()));
        findViewById(R.id.register).setOnClickListener(v -> launcher.launch(new Intent(this, RegisterActivity.class)));
    }

    @Override
    public void loginSuccess(String token) {
        SPUtils.getInstance().putString("token", token);
        Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
        startActivity(new Intent(this, MainActivity2.class));
    }

    @Override
    public void loginFailure(Throwable t) {
        Toast.makeText(this, t.getMessage(), Toast.LENGTH_SHORT).show();
    }
}